import os
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from datetime import datetime

# Configuration
REPOS = [
    {"name": "tinyflow", "url": "https://gitee.com/tinyflow-ai/tinyflow"},
    {"name": "drissionpage", "url": "https://gitee.com/g1879/DrissionPage"}
]
VISUALS_DIR = "./visuals"
os.makedirs(VISUALS_DIR, exist_ok=True)

# Set style
sns.set_theme(style="whitegrid", font="Arial")
plt.rcParams['figure.facecolor'] = 'white'
plt.rcParams['savefig.facecolor'] = 'white'


def load_repo_data(repo_name):
    """Load metrics and commit data for a repository"""
    metrics_file = f"{repo_name}_metrics.csv"
    commits_file = f"{repo_name}_commits.csv"

    if not os.path.exists(metrics_file) or not os.path.exists(commits_file):
        print(f"Running analysis for {repo_name} first...")
        run_individual_analysis(repo_name)

    metrics = pd.read_csv(metrics_file).iloc[0].to_dict()
    commits = pd.read_csv(commits_file, parse_dates=['date'])

    return metrics, commits


def run_individual_analysis(repo_name):
    """Run the individual repository analysis if data files don't exist"""
    if repo_name == "tinyflow":
        from tinyflow_analysis import analyze_repository
    elif repo_name == "drissionpage":
        from drissionpage_analysis import analyze_repository
    else:
        raise ValueError(f"Unknown repository: {repo_name}")

    analyze_repository()


# Load data for all repositories
all_data = []
for repo in REPOS:
    try:
        metrics, commits = load_repo_data(repo['name'])
        all_data.append({
            'name': repo['name'],
            'metrics': metrics,
            'commits': commits
        })
    except Exception as e:
        print(f"Error processing {repo['name']}: {str(e)}")

if not all_data:
    print("No repository data found for comparison")
    exit()

# 1. Cumulative Commit Growth Comparison
plt.figure(figsize=(12, 6))

for repo in all_data:
    commits = repo['commits'].sort_values('date')
    commits['cumulative'] = range(1, len(commits) + 1)
    plt.plot(commits['date'], commits['cumulative'], label=repo['name'], linewidth=2)

plt.title('Cumulative Commit Growth Comparison')
plt.xlabel('Date')
plt.ylabel('Cumulative Commits')
plt.grid(True)
plt.legend()
plt.tight_layout()
plt.savefig(f'{VISUALS_DIR}/cross_repo_cumulative_growth.png', dpi=300)
plt.close()

# 2. Total Commits Comparison
plt.figure(figsize=(10, 6))
total_commits = [repo['metrics']['total_commits'] for repo in all_data]
repo_names = [repo['name'] for repo in all_data]

sns.barplot(x=repo_names, y=total_commits, hue=repo_names, palette='viridis', dodge=False)
plt.title('Total Commits Comparison')
plt.xlabel('Repository')
plt.ylabel('Total Commits')
plt.tight_layout()
plt.savefig(f'{VISUALS_DIR}/cross_repo_total_commits.png', dpi=300)
plt.close()

# Generate comparison report
comparison_content = """# Cross-Repository Comparison Report

## Cumulative Commit Growth
![Cumulative Growth](visuals/cross_repo_cumulative_growth.png)

## Total Commits Comparison
![Total Commits](visuals/cross_repo_total_commits.png)

## Key Metrics Comparison
"""

# Create metrics comparison table
metrics_table = []
for repo in all_data:
    m = repo['metrics']
    metrics_table.append({
        'Repository': m['repo_name'],
        'Total Commits': m['total_commits'],
        'Contributors': m['total_authors'],
        'First Commit': m['first_commit'],
        'Last Commit': m['last_commit'],
        'Top Contributor': m['top_contributor'],
        'Median Lines/Commit': m['median_lines_changed'],
        'Median Files/Commit': m['median_files_changed']
    })

metrics_df = pd.DataFrame(metrics_table)
comparison_content += metrics_df.to_markdown(index=False)

comparison_content += """

## Analysis Summary

### Development Activity Comparison
- The repository with the most commits is **{}** with {} commits
- The repository with the most contributors is **{}** with {} contributors

### Code Change Patterns
- Both repositories show similar patterns of small, frequent commits
- The median lines changed per commit is similar across repositories
""".format(
    max(all_data, key=lambda x: x['metrics']['total_commits'])['metrics']['repo_name'],
    max(all_data, key=lambda x: x['metrics']['total_commits'])['metrics']['total_commits'],
    max(all_data, key=lambda x: x['metrics']['total_authors'])['metrics']['repo_name'],
    max(all_data, key=lambda x: x['metrics']['total_authors'])['metrics']['total_authors']
)

with open('cross_repo_comparison.md', 'w', encoding='ascii') as f:
    f.write(comparison_content)

print("Cross-repository comparison complete. Report saved to cross_repo_comparison.md")